package jprint.base.label;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import javax.annotation.Nonnull;
import jprint.base.AppContext;
import jprint.base.util.JsonUtil;

/**
 * @author zw-zheng
 * Created on 2020-12-01
 */
public class LabelService {

    private static LabelService sInstance;
    private AppContext appContext;
    private File baseDir;

    LabelService() {
    }

    public static LabelService getInstance(@Nonnull AppContext appContext) {
        if (sInstance == null) sInstance = new LabelService();
        sInstance.appContext = appContext;
        sInstance.baseDir = appContext.getWebRoot();
        return sInstance;
    }

    public InputStream getFile(String path) {
        File file = new File(baseDir, "label/" + path);
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void post(Map<String, String> params) {
        saveLabel(Label.from(params));
    }

    private void saveLabel(Label label) {
        // String name = label.getName();
        String json = JsonUtil.toJsonString(label);
        File target = new File(baseDir, "label/default-format.json");
        try {
            OutputStream out = new FileOutputStream(target);
            out.write(json.getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Label labelFormat(String name) {
        File file = new File(baseDir, "label/" + name + ".json");
        return Label.from(file);
    }
}
